<template>
  <div>
    <!-- 隐藏的文件上传组件，用于处理图片上传 -->
    <input
      type="file"
      accept="image/*"
      style="display: none"
      ref="upload"
      @change="handleFileChange"
    />
    <!-- 富文本编辑器容器 -->
    <div class="editor" ref="editorContainer"></div>
  </div>
</template>

<script>
import Quill from "quill";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Editor",
  props: {
    value: {
      type: String,
      default: "",
    },
    height: {
      type: Number,
      default: null,
    },
    minHeight: {
      type: Number,
      default: null,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    fileSize: {
      type: Number,
      default: 5,
    },
    type: {
      type: String,
      default: "url",
    },
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      quill: null,
      currentContent: "",
      uploadType: "",
    };
  },
  computed: {
    editorOptions() {
      return {
        theme: "snow",
        bounds: document.body,
        debug: "warn",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ indent: "-1" }, { indent: "+1" }],
            [{ size: ["small", false, "large", "huge"] }],
            [{ header: [1, 2, 3, 4, 5, 6, false] }],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            ["clean"],
            // ["image"], // 保留图片按钮
          ],
        },
        placeholder: "请输入内容",
        readOnly: this.readOnly,
      };
    },
    containerStyles() {
      const styles = {};
      if (this.minHeight) {
        styles.minHeight = `${this.minHeight}px`;
      }
      if (this.height) {
        styles.height = `${this.height}px`;
      }
      return styles;
    },
  },
  watch: {
    value: {
      handler(newValue) {
        if (newValue !== this.currentContent) {
          this.currentContent = newValue;
          if (this.quill) {
            this.quill.setContents(
              this.quill.clipboard.convert(newValue || "")
            );
          }
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.initQuill();
  },
  beforeDestroy() {
    if (this.quill) {
      this.quill.destroy();
      this.quill = null;
    }
  },
  methods: {
    initQuill() {
      const container = this.$refs.editorContainer;
      this.quill = new Quill(container, this.editorOptions);

      // 自定义图片上传处理
      if (this.type === "url") {
        const toolbar = this.quill.getModule("toolbar");
        toolbar.addHandler("image", this.handleImageUpload);
      }

      // 监听内容变化
      this.quill.on("text-change", (delta, oldDelta, source) => {
        const html = container.children[0].innerHTML;
        this.currentContent = html;
        this.$emit("input", html);
        this.$emit("on-change", {
          html,
          text: this.quill.getText(),
          quill: this.quill,
        });
      });

      // 其他事件监听
      this.quill.on("selection-change", (range, oldRange, source) => {
        this.$emit("on-selection-change", range, oldRange, source);
      });
    },

    handleImageUpload() {
      this.$refs.upload.click();
    },

    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        if (this.validateFileSize(file)) {
          this.uploadFile(file);
        }
        this.$refs.upload.value = null; // 重置输入框，允许重新选择同一文件
      }
    },

    validateFileSize(file) {
      const sizeInMB = file.size / 1024 / 1024;
      if (sizeInMB > this.fileSize) {
        this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
        return false;
      }
      return true;
    },

    uploadFile(file) {
      const formData = new FormData();
      formData.append("file", file);

      const config = {
        headers: {
          ...this.headers,
          "Content-Type": "multipart/form-data",
        },
      };

      this.$http
        .post(this.uploadUrl, formData, config)
        .then((response) => {
          if (response.data.code === 200) {
            const imageUrl =
              process.env.VUE_APP_BASE_API + response.data.fileName;
            this.insertImage(imageUrl);
          } else {
            this.$message.error("图片上传失败");
          }
        })
        .catch(() => {
          this.$message.error("图片上传失败");
        });
    },

    insertImage(url) {
      const range = this.quill.getSelection();
      if (range !== null) {
        this.quill.insertEmbed(range.index, "image", url);
        this.quill.setSelection(range.index + 1);
      }
    },
  },
};
</script>

<style>
.editor {
  white-space: pre-wrap !important;
  line-height: normal !important;
}

.ql-toolbar {
  white-space: pre-wrap !important;
  line-height: normal !important;
}

.quill-img {
  display: none;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0;
  content: "保存";
  padding-right: 0;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
</style>
